package com.topvision.idcard;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.topvision.idcard.bean.PicBean;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import Decoder.BASE64Encoder;
import okhttp3.Response;

/**
 * User: jack(jackgu@topvision-cv.com)
 * Date: 2016-11-21
 * Time: 15:25
 */

/**
 * 拍照回調方法
 *
 * @author jack
 *         create at 2016/11/21 14:47
 */
public class TakePhotoCallback implements Camera.PictureCallback {
    //缩略图的大小
    public static final int DISPLAY_WIDTH = 400;
    public static final int DISPLAY_HEIGHT = 400;
    Context context;
    ImageView albumIv;
    Bitmap currPhoto;
    BASE64Encoder encoder = null;
    int count;
    byte[] preData;
    ICameraActivity iCameraActivity;
    public TakePhotoCallback(Context context,ICameraActivity iCameraActivity) {
        this.context = context;
        this.iCameraActivity = iCameraActivity;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        try {
            count++;
            Bundle bundle = new Bundle();
            bundle.putByteArray("bytes", data);
            // 将图片字节数据保存在bundle当中，实现数据交换
            String preFixFileName = String.valueOf(new Date().getTime());
            // 保存图片到sd卡中
            File file = saveToSDCard(context, data, preFixFileName);
            Utils.showTips(context,"照片已上传");
//            Toast.makeText(context,"保存了照片",Toast.LENGTH_SHORT).show();
            fileScan(context, file.getPath());
            upload(data);
            camera.startPreview();
            CameraActivity.safeToTakePicture = true;
        } catch (Exception e) {
            e.printStackTrace();
            CameraActivity.safeToTakePicture = true;
        }
    }

    private void upload(final byte[] data) {
        //上传服务器
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (encoder == null) {
                        encoder = new BASE64Encoder();
                    }
                    System.out.println(CameraActivity.TYPE);
                    //身份证
                    if (CameraActivity.TYPE.equals(CameraActivity.TYPE_ORC)) {
//                        Response response = OkHttpUtils.post().url("http://112.80.35.3:8828/ocr")
//                                .addParams("app_id", "user")
//                                .addParams("app_secret", "12345")
//                                .addParams("isCheckPrint", "1")
//                                .addParams("img", encoder.encode(data)).build()
//                                .connTimeOut(100000).execute();
//                        if (response.code() == 200) {
//                            String result = response.body().string();
//                            System.out.println(result);
//                            if (result.contains("\"type\":\"1\"")) {
//                                Intent intent = new Intent();
//                                intent.setAction("frontBean");
//                                intent.putExtra("result", result);
//                                context.sendBroadcast(intent);
//                            } else if (result.contains("\"type\":\"0\"")) {
//                                Intent intent = new Intent();
//                                intent.setAction("backBean");
//                                intent.putExtra("result", result);
//                                context.sendBroadcast(intent);
//                            } else {
//                                Utils.showTips(context,"识别不出结果");
//                            }
//                        }
                        //人脸比对（相似度）
                        //第一次
                        if (count == 1) {
                            preData = data;
                        } else if (count == 2) {
                            CameraActivity.comparingFace = true;
                            count = 0;
                            //第二次(比对中)
                            Intent intent2 = new Intent("comparing");
                            context.sendBroadcast(intent2);
                            Response response = OkHttpUtils.post().url("http://112.80.35.3:8828/face/tool/compare")
                                    .addParams("app_id", "user")
                                    .addParams("app_secret", "12345")
                                    .addParams("isCheckPrint", "1")
                                    .addParams("imgA", encoder.encode(preData))
                                    .addParams("imgB", encoder.encode(data)).build()
                                    .execute();
                            if (response.code() == 200) {
                                String result = response.body().string();
                                System.out.println(result);
                                Gson gson = new Gson();
                                PicBean picBean = gson.fromJson(result, PicBean.class);
                                if (picBean.getResult()== 0) {
                                    //这里我们需要显示图片出来
                                    System.out.println("显示结果");
//                                    Intent intent = new Intent("picBean");
//                                    intent.putExtra("bytes1", preData);
//                                    intent.putExtra("bytes2", data);
//                                    intent.putExtra("result", result);
//                                    context.sendBroadcast(intent);
                                    iCameraActivity.showResultPic(preData,data,result);

                                } else {
                                    Intent intent = new Intent("completeCompare");
                                    context.sendBroadcast(intent);
                                }
                            } else {
                                Intent intent = new Intent("completeCompare");
                                context.sendBroadcast(intent);
                            }
                            CameraActivity.comparingFace = false;
                        }
                    } else if (CameraActivity.TYPE.equals(CameraActivity.TYPE_BANK_CAR)) {
                        CameraActivity.comparingFace = true;
                        //正在识别
                        Intent intent2 = new Intent("comparing");
                        context.sendBroadcast(intent2);
                        Response response = OkHttpUtils.post().url("http://112.80.35.3:8828/ocr/bankcard")
                            .addParams("app_id", "user")
                            .addParams("app_secret", "12345")
                            .addParams("img", encoder.encode(data)).build()
                            .connTimeOut(100000).execute();
                        if (response.code() == 200) {
                            String result = response.body().string();
                            System.out.println(result);
                            if (result.contains("\"info\":\"success\"")) {
                                Intent intent = new Intent();
                                intent.setAction("bankBean");
                                intent.putExtra("result", result);
                                context.sendBroadcast(intent);
                            } else {
                                Intent intent = new Intent("completeCompare");
                                context.sendBroadcast(intent);
                            }
                        }
                        CameraActivity.comparingFace = false;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Intent intent = new Intent("completeCompare");
                    context.sendBroadcast(intent);
                    Utils.showTips(context,"无网络连接");
                    CameraActivity.comparingFace = false;
                }
            }
        }).start();
    }


    public static final String TAKE_PHOTO_FOLDER = Environment.getExternalStorageDirectory() + File.separator + "topvision/";
    /**
     * 将拍下来的照片存放在SD卡中
     *
     * @param data
     * @throws IOException
     */
    public static File saveToSDCard(Context context, byte[] data, String fileName) throws IOException {
        String filename = fileName + ".jpg";
        File fileFolder = new File(TAKE_PHOTO_FOLDER);
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
            fileScan(context, fileFolder.getPath());
        }
        //将byte数组写入到某个文件当中,
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
        return jpgFile;

    }

    /**
     * 扫描 mtp下的文件，在保存文件到 sd卡下后，不能显示，故这里触发一下扫描机制，让手机连上电脑后，就可以读出文件了
     *
     * @param fName 文件路径
     *              create at 2017/2/7 9:22
     */
    public static void fileScan(Context context, String fName) {
        File file = new File(fName);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            if (file.isDirectory()) {
                scanDirAsync(context, fName);
            }else{
                Uri data = Uri.parse("file:///" + fName);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, data));
            }

        } else {
            //异步扫描目录
            if (file.isDirectory()) {
                scanDirAsync(context, fName);
            } else {
                MediaScannerConnection.scanFile(context,
                        new String[]{fName}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                                Log.i("ExternalStorage", "Scanned " + path + ":");
                                Log.i("ExternalStorage", "-> uri=" + uri);
                            }
                        });
            }

        }

    }

    public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";
    public static void scanDirAsync(Context ctx, String dir) {
        Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
        scanIntent.setData(Uri.fromFile(new File(dir)));
        ctx.sendBroadcast(scanIntent);
    }
}
